import xml.etree.ElementTree as ET


class CommentedTreeBuilder(ET.TreeBuilder):
    def comment(self, data):
        self.start(ET.Comment, {})
        self.data(data)
        self.end(ET.Comment)


def register_all_namespaces(filename):
    namespaces = dict([node for _, node in ET.iterparse(filename, events=["start-ns"])])
    for ns in namespaces:
        ET.register_namespace(ns, namespaces[ns])


def change_one_xml(xml_path, group_dw, artifact_dw, update_content):
    # 打开xml文档
    parser = ET.XMLParser(target=CommentedTreeBuilder())
    tree = ET.parse(xml_path, parser=parser)
    # tree = ET.parse(xml_path)
    root = tree.getroot()
    location_name = root.tag[: root.tag.index("}") + 1]
    locationUrl = location_name[1:-1]
    for node in root.findall(".//" + location_name + "dependency"):
        groupIdNode = node.find("." + location_name + "groupId")
        artifactNode = node.find("." + location_name + "artifactId")
        if artifactNode.text == artifact_dw and groupIdNode.text == group_dw:
            versionNode = node.find("" + location_name + "version")
            versionNode.text = update_content
        # print(node.tag.split('}')[-1])
    # 查找修改路劲
    #    sub1 = root.find(xml_dw)
    # 修改标签内容
    #    sub1.text = update_content
    # 保存修改
    # register_all_namespaces(None)
    tree.write(
        xml_path,
        xml_declaration=True,
        encoding="utf-8",
        method="xml",
        default_namespace=locationUrl,
    )


# 欲修改文件
xml_path = "pom.xml"
# 修改文件中的xpath定位
group_id = "com.yapai"
artifact_id = "syn-thingsboard"
# 想要修改成什么内容
update_content = "twgdh"
change_one_xml(xml_path, group_id, artifact_id, update_content)
